package com.shoesmail.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.shoesmail.enums.RoleEnum;

import java.util.Date;

/**
 * @author ：xxx
 * @description：TODO
 * @date ：2025/9/17 9:16
 */
public class JwtUtil {
    private static final long EXPIRE_TIME = 30 * 24 * 60 * 60 * 1000;

    //密钥
    private static final String SECRET = "jwt_secret";

    private static final String USER_ID_KEY = "userId";

    private static final String USER_ROLE_KEY = "role";

    public static String sign(String userId, RoleEnum role) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    // 将 user id 保存到 token 里面
                    .withClaim(USER_ID_KEY, userId)
                    .withClaim(USER_ROLE_KEY,role.getCode())
                    // 五分钟后token过期
                    .withExpiresAt(date)
                    // token 的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getUserId(String token) {

        try {
            String userId = JWT.decode(token).getClaim(USER_ID_KEY).asString();
            return userId;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static RoleEnum getRole(String token){
        try {
            Integer integer = JWT.decode(token).getClaim(USER_ROLE_KEY).asInt();
            return RoleEnum.getRole(integer);
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static boolean checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    // .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception) {
            return false;
        }

    }
}
